// pages/scheduleManage/scheduleManage.js
var app = getApp();
let load = true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bannerSchedule: app.globalData._network_path + 'banner-schedule.png',//banner图片
    weight1: app.globalData._network_path + 'weight1.png',
    weight2: app.globalData._network_path + 'weight2.png',
    weight3: app.globalData._network_path + 'weight3.png',
    page: 1,
    pageSize: 10,
    chooseDate: '',
    dateList: [], //日历列表
    totaltDate: '', //今日日程统计
    orderList: [],
    empty: true,
    hasMore: false,
    loading: false,
    loadShow: false,
    token: wx.getStorageSync('token'),
    lat1: '',
    lng1: '',
    reasonIndex: "",
    reasonShow: true,//
    chargebackId: '',//退还订单号
    remarks: '',//退还备注
    tipShow: true,//
    dropShow: true,//上门

    scrollLeft:0,//滚动条位置

    callShow: false,//拨打电话弹窗显示
    callItem: '',// 点击拨打的工单详情
    callIndex: 0,//选择联系人|紧急联系人
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.getDateList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    // 当没有数据时,不再请求
    var hasMore = that.data.hasMore;
    if (!hasMore) {
      return false;
    }

    var page = that.data.page + 1;
    that.setData({
      page: page,
      loading: true
    })
    that.getScheduleList();
  },

  //获取日程表
  getDateList() {
    var that = this;
    app.ajax({
      url: "Engineer/Schedule/date",
      data: {},
      success: function (res) {
        if(res.data.code == 1000){
          that.setData({
            dateList: res.data.data,
            chooseDate: that.data.chooseDate || res.data.data[0].date
          })
          that.getTotaltDate();
          that.getScheduleList();
        }
      }
    })
  },
  //获取今日日程统计
  getTotaltDate() {
    var that = this;
    app.ajax({
      url: "Engineer/Schedule/statistics",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            totaltDate: res.data.data
          })
        }
      }
    })
  },
  //获取日程数据
  getScheduleList() {
    var that = this;
    app.ajax({
      url: "Engineer/Schedule/getSchedule",
      load: load,
      msg: '数据加载中...',
      data: {
        date: that.data.chooseDate,
        page: that.data.page,
        row: that.data.pageSize
      },
      success: function (res) {
        if (res.data.code == 1000) {
          if (that.data.page == 1) {
            that.setData({
              orderList: res.data.data.data,
              empty: false
            });
          } else {
            that.setData({
              orderList: that.data.orderList.concat(res.data.data.data),
              empty: false
            });
          }
          // 是否加载更多
          var hasMore = true;
          if (res.data.data.data.length < that.data.pageSize) {
            hasMore = false;
          }
          that.setData({
            hasMore: hasMore,
            loading: false
          });
          load = false;
        } else {
          if (that.data.page == 1) {
            that.setData({
              hasMore: false,
              loading: false,
              empty: true
            })
          } else {
            that.setData({
              hasMore: false,
              loading: false,
              empty: false
            })
          }
        }
        that.setData({
          loadShow: true
        })
      }
    })
  },
  // 选择天
  changedate(e){
    var that = this;
    that.setData({
      chooseDate: e.currentTarget.dataset.date
    })
    that.getScheduleList();
  },
  // 打开拨打电话弹窗
  openCall(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    console.log('index', index);
    var orderList = that.data.orderList;
    var item = orderList[index];
    console.log('item', item)
    that.setData({
      callShow: true,
      callItem: item,
      callIndex: 0,
    })
  },
  // 关闭拨打电话弹窗
  cancelCall() {
    var that = this;
    that.setData({
      callShow: false,
      callItem: false
    })
  },
  // 跳转紧急联系人
  goEmergency() {
    var that = this;
    var callItem = that.data.callItem;
    wx.navigateTo({
      url: '/pages/order/emergencyContact/emergencyContact?user_id=' + callItem.user_id + '&work_order_id=' + callItem.work_order_id + '&emergency_contact=' + JSON.stringify(callItem.emergency_contact),
    })
    that.cancelCall();
  },
  // 切换选择联系人|紧急联系人
  callChoose(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    that.setData({
      callIndex: index
    })
  },
  // 确认选中拨打电话
  sureTelphone() {
    var that = this;
    var index = that.data.callIndex;
    var callItem = that.data.callItem;
    var number = callItem.contact_number;
    if (index == 1) {
      number = callItem.emergency_contact.tel
    }
    wx.makePhoneCall({
      phoneNumber: number,
    })
    that.cancelCall();
  },
  //联系他
  telPhone: function (e) {
    let phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },
  //跳转添加日程
  addDate(){
    var that = this;
    wx.navigateTo({
      url: '/pages/subpackage/pages/date/addSchedule/addSchedule?date=' + that.data.chooseDate,
    })
  },
  //确认预约时间
  amendTime(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/order/amendTime/amendTime?id=' + id,
    })
  },
  //修改预约时间
  editTime(e){
    var id = e.currentTarget.dataset.id;
    var order_id = e.currentTarget.dataset.order_id;
    var schedule_weight = e.currentTarget.dataset.weight;
    wx.navigateTo({
      url: '/pages/subpackage/pages/order/editTime/editTime?work_order_id=' + order_id + '&id=' + id + '&schedule_weight=' + schedule_weight + '&date=' + this.data.chooseDate,
    })
  },
  //退还订单
  chargeback(e) {
    let that = this;
    let reasonShow = false;
    let id = e.currentTarget.dataset.id;
    that.setData({
      reasonShow: reasonShow,
      chargebackId: id
    })
  },
  //退还原因
  bindPickerChange: function (e) {
    let that = this;
    let reasonIndex = e.detail.value;
    that.setData({
      reasonIndex: reasonIndex
    })
  },
  //退换备注
  inputRemarks: function (e) {
    var that = this;
    var remarks = e.detail.value;
    that.setData({
      remarks: remarks
    });
  },
  //确定退还
  confirm: function (e) {
    let that = this;
    let reasonShow = true;
    let tipShow = false;
    var id = that.data.chargebackId;
    var reasonIndex = that.data.reasonIndex;
    var remarks = that.data.remarks;
    app.saveFormId(e.detail.formId);
    if (reasonIndex == '' || remarks == '') {
      app.showToast("请填写完整信息", "none", 2000, function () { });
      return;
    }
    app.ajax({
      url: 'Engineer/Workorder/backOrderApply',
      data: {
        work_order_id: id,
        reason_id: reasonIndex,
        remark: remarks
      },
      header: {
        'token': that.data.token
      },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast("退单成功", "none", 2000, function () { });
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });

        }

      }
    })
    that.setData({
      reasonShow: reasonShow,
      tipShow: tipShow,
      remarks: '',
      reasonIndex: ''
    })
    timer = setTimeout(function () {
      let tipShow = true;
      that.setData({
        tipShow: tipShow
      })
      that.getOrderList();
    }, 2000);
  },
  //取消退还
  cancel: function () {
    let that = this;
    let reasonShow = true;
    that.setData({
      reasonShow: reasonShow,
      remarks: '',
      reasonIndex: ''
    })
  },
  //查看详情
  orderDetail(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/order/orderDetail/orderDetail?id=' + id,
    })
  },
  //上门
  dropIn: function (e) {
    let that = this;
    let dropShow = false;
    var id = e.currentTarget.dataset.id;
    var lat1, lng1;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        lat1 = res.latitude;
        lng1 = res.longitude;

        that.setData({
          dropShow: dropShow,
          work_order_id: id,
          lat1: lat1,
          lng1: lng1
        })
      }
    });
  },
  //确定上门
  dropConfirm: function (e) {
    let that = this;
    let dropShow = true;
    var id = that.data.work_order_id;
    var lat1 = that.data.lat1;
    var lng1 = that.data.lng1;
    app.saveFormId(e.detail.formId);
    app.ajax({
      url: 'Engineer/Workorder/goHome',
      data: {
        work_order_id: id,
        lat: lat1,
        lng: lng1
      },
      header: {
        'token': that.data.token
      },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast("确认成功", "none", 2000, function () { });
          wx.setStorageSync('tabIndex', 2);
          that.getOrderList();
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });
        }
      }
    })

    that.setData({
      dropShow: dropShow
    })
  },
  //取消上门
  dropCancel: function () {
    let that = this;
    let dropShow = true;
    that.setData({
      dropShow: dropShow
    })
  },
  // 确认安装地址
  confirmAddress(e) {
    var that = this;
    var order_id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    if (type != 2) {
      type = 1;
    }
    wx.navigateTo({
      url: '/pages/order/confirmAddress/confirmAddress?order_id=' + order_id + '&type=' + type,
    })
  },

  // 点击按钮切换到下一个view
  scrollData(){
    var that = this;
    that.setData({
      scrollLeft: Math.round(that.data.scrollLeft/49)*49 + 49*7,
    })
  },
  
  // 滚动条滚动后触发
  scroll(e) {
    var that = this;
    clearTimeout(that.data.scrollLeft);
    that.data.scrollLeft = setTimeout(() => {
      that.setData({
        scrollLeft: Math.round(e.detail.scrollLeft / 49) * 49,
      })
    }, 300)
  },

})